<?php
namespace app\user\middleware;

use app\common\exception\UnauthorizedException;
use app\user\logic\user\Token as UserToken;
use app\user\logic\user\VipUser;

class BindLoginUser
{
    public function handle($request, \Closure $next)
    {

        // 进行登录验证
        $ak = $request->header('E-USER-AK', '');
        $sk = $request->header('E-USER-SK', '');

        // 如果引用了路由登录排除中间件,则不抛出异常
        if ($request->needLogin === false) {
            $request->user = false;
            if ($ak && $sk) {
                // 获取用户
                $user          = app(UserToken::class)->getUserWithToken($ak, $sk);
                $request->user = $user;
                $request->mid  = $user->id ?? 0;
            }
            return $next($request);
        }

        if (!$ak || !$sk) {

            throw new UnauthorizedException(null, 402);
        }

        // 获取用户
        $user = app(UserToken::class)->getUserWithToken($ak, $sk);
        if ($user === false) {
            throw new UnauthorizedException(null, 402);
        }

        $request->mid  = $user->id ?? 0;

        // 会员情况
        $user->is_vip  = app(VipUser::class)->isVip();

        $request->user = $user;

        return $next($request);
    }

}
